/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.games.esmi.ieat.indicatorrelations;

import com.vaadin.terminal.Sizeable;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.Tree;
import com.vaadin.ui.VerticalLayout;
import eu.games.esmi.ieat.indicatorrelations.data.Correlation;
import eu.games.esmi.ieat.indicatorrelations.data.CorrelationMiner;
import eu.games.esmi.ieat.indicatorrelations.ui.DatePopupInputPrompt;
import eu.games.esmi.ieat.indicatorrelations.ui.NumericTextField;
import eu.games.esmi.ieat.indicatorvalues.IndicatorTreeGenerator;
import eu.games.esmi.ieat.indicatorvalues.data.EMF;
import it.polimi.games.epkb.entityClasses.StoredValues;
import it.polimi.games.epkb.manager.EPKBmanager;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Set;

/**
 *
 * @author user
 */
public class CorrelationDesignTab extends Panel {
    
    public NumericTextField sampling = new NumericTextField("Sampling period (sec)", 30);
//    public DatePopupInputPrompt start = new DatePopupInputPrompt("Start time", new Date(new Date().getTime() - 500 * sampling.getNumber() * 1000));
//    public DatePopupInputPrompt end = new DatePopupInputPrompt("End time", new Date());
    public DatePopupInputPrompt start = new DatePopupInputPrompt("Start time", new GregorianCalendar(2012,5,12,17,0,0).getTime());
    public DatePopupInputPrompt end = new DatePopupInputPrompt("End time", new GregorianCalendar(2012,5,12,18,0,0).getTime());
    public Tree treeDx = new IndicatorTreeGenerator().createTree(IndicatorTreeGenerator.INDICATOR_TREE);
    public Tree treeSx = new IndicatorTreeGenerator().createTree(IndicatorTreeGenerator.INDICATOR_TREE);
    public TextArea definedCorrelationsTextArea = new TextArea("Defined correlations");

    private String operand = " <==> ";
    
    public CorrelationDesignTab() {
        super();
        init();
    }
    
    public void init() {
        
        HorizontalLayout h = new HorizontalLayout();
        h.setSpacing(true);

        HorizontalLayout h1 = new HorizontalLayout();
        h1.setSpacing(true);
//////            treeSx.addListener(new ValueChangeListener() {
//////            public void valueChange(ValueChangeEvent event) {
//////                Tree t = (Tree) event.getProperty();
//////                // enable if something is selected, returns a set
//////                x = ((Set<?>) t.getValue()).size();
//////            }
//////            });
            h1.addComponent(treeSx);

            Button correlateButton = new Button("Correlate");
            correlateButton.addListener(new Listener() {

                public void componentEvent(Event event) {
                //PROVA
                //Tabs.INSTANCE.correlationAnalysisTab.addCorrelationToTable(new Correlation("[PROVA] Sampling time", sampling.getNumber().toString()));
                    for (Object sx : ((Set<Object>)treeSx.getValue()).toArray()) {
                        for (Object dx : ((Set<Object>)treeDx.getValue()).toArray()) {
                            addDefinedCorrelation(sx.toString(), dx.toString());
                    }
                }
            }});
            
            h1.addComponent(correlateButton);

            h1.addComponent(treeDx);

            VerticalLayout v14 = new VerticalLayout();
            v14.setSpacing(true);

                v14.addComponent(start);
                
                v14.addComponent(end);

                v14.addComponent(sampling);

            h1.addComponent(v14);

        h.addComponent(h1);
        //this.addComponent(h1);

        HorizontalLayout h2 = new HorizontalLayout();
        h2.setSpacing(true);

            VerticalLayout v21 = new VerticalLayout();
            v21.setSpacing(true);

                //v21.addComponent(new Label("Defined correlations"));

                definedCorrelationsTextArea.setWidth(320, Sizeable.UNITS_PIXELS);
                v21.addComponent(definedCorrelationsTextArea);

            h2.addComponent(v21);

            VerticalLayout v22 = new VerticalLayout();
            v22.setSpacing(true);

                Button deleteButton = new Button("Delete");
                deleteButton.addListener(new Listener() {
                    public void componentEvent(Event event) {
                        definedCorrelationsTextArea.setValue("") ;
                    }
                });
                v22.addComponent(deleteButton);
                
                Button startButton = new Button("Start");
                startButton.addListener(new Listener() {
                    
                    public void componentEvent(Event event) {
                        
                        EPKBmanager epkb = new EPKBmanager(EMF.PU_NAME);
                        long startTime = start.getDatetime().getTime();
                        long endTime = end.getDatetime().getTime();
                        long samplingTime = sampling.getNumber().longValue() * 1000;
                        MainIndicatorRelations.getCorrelationAnalysisTab().clearCorrelationTable();
                        for(String definedCorrelation : ((String)(definedCorrelationsTextArea.getValue())).split("\n\r")) {
                            if (definedCorrelation.contains(operand)) {
                                String indicatorSx = definedCorrelation.split(operand)[0];
                                String indicatorDx = definedCorrelation.split(operand)[1];
                                getWindow().showNotification("Correlating " + indicatorSx + " and " + indicatorDx + "...");
                                List<Double> scorelist1 = new ArrayList<Double>();
                                List<Double> scorelist2 = new ArrayList<Double>();
                                List<Long> delta1 = new ArrayList<Long>();
                                List<Long> delta2 = new ArrayList<Long>();
                                for (long t = startTime; t < endTime; t = t + samplingTime) {
                                    System.out.print(new Date(t) + " >>> " + indicatorSx);
                                    StoredValues storedvalue1 = epkb.getIndicator(indicatorSx.split("-")[0], indicatorSx.split("-")[1], new Date(t));
                                    scorelist1.add(storedvalue1.getComputedValue().doubleValue());
                                    System.out.print(new Date(t) + " >>> " + indicatorDx);
                                    StoredValues storedvalue2 = epkb.getIndicator(indicatorDx.split("-")[0], indicatorDx.split("-")[1], new Date(t));
                                    scorelist2.add(storedvalue2.getComputedValue().doubleValue());
                                    delta1.add(storedvalue1.getDefinitionTime().getTime() - t);
                                    delta2.add(storedvalue2.getDefinitionTime().getTime() - t);
                                }
                                double[] scores1 = new double[scorelist1.size()];
                                for (int i = 0; i < scores1.length; i++) {
                                    scores1[i] = scorelist1.get(i);
                                }
                                double[] scores2 = new double[scorelist2.size()]; 
                                for (int i = 0; i < scores2.length; i++) {
                                    scores2[i] = scorelist2.get(i);
                                }
                                MainIndicatorRelations.getCorrelationAnalysisTab().addCorrelationToTable(new Correlation(indicatorSx + operand + indicatorDx, CorrelationMiner.getPearsonCorrelation(scores1, scores2) + ""));
                            }
                        }
                        getWindow().showNotification("Correlation data available");
                    }
                });
                v22.addComponent(startButton);

            h2.addComponent(v22);

        h.addComponent(h2);
        //this.addComponent(h2);

        this.addComponent(h);
    }
    
    private boolean hasDefinedCorrelation(String definedCorrelation) {
        String list = definedCorrelationsTextArea.getValue().toString();
        return list.contains(definedCorrelation) || 
                list.contains(definedCorrelation.split(operand)[1] + operand + definedCorrelation.split(operand)[0]);
    }
    
    private void addDefinedCorrelation(String sx, String dx) {        
        String definedCorrelation = sx + operand + dx;
        if (!hasDefinedCorrelation(definedCorrelation))
            definedCorrelationsTextArea.setValue(definedCorrelationsTextArea.getValue() + 
                    (definedCorrelationsTextArea.getValue() != "" ? "\n\r" : "") + definedCorrelation);
    }
}
